package com.example.jobback.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;

/**
 * @ClassName: SecureEncryptionUtil
 * @Description: AES工具类
 * @Author: lhb
 * @Date: 2025/5/10
 */

public class SecureEncryptionUtil {

    private static final String CHARSET = "UTF-8";
    private static final int ITERATION_COUNT = 65536;
    private static final int KEY_LENGTH = 256; // AES 256位密钥

    /**
     * @Description: 使用PBKDF2从secret生成密钥
     * @param secret
     * @return SecretKeySpec
     * @Author lhb
     * @CreateTime 2025/5/30 16:22
     */
    public static SecretKeySpec generateKey(String secret) throws Exception {
        char[] password = secret.toCharArray();
        // 使用一个固定的盐值（可以是任何固定字符串）
        byte[] salt = "boss_salt_value".getBytes(StandardCharsets.UTF_8);
        KeySpec spec = new PBEKeySpec(password, salt, ITERATION_COUNT, KEY_LENGTH);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        byte[] keyBytes = factory.generateSecret(spec).getEncoded();
        return new SecretKeySpec(keyBytes, "AES");
    }


    /**
     * @Description: 加密
     * @param data
     * @param secret
     * @return String
     * @Author lhb
     * @CreateTime 2025/5/30 16:23
     */
    public static String encrypt(String data, String secret) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec key = generateKey(secret);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }


    /**
     * @Description: 解密
     * @param encryptedData
     * @param secret
     * @return String
     * @Author lhb
     * @CreateTime 2025/5/30 16:23
     */
    public static String decrypt(String encryptedData, String secret) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec key = generateKey(secret);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes, CHARSET);
    }
}
